package com.x.xiaoshuo.widget.readview.aim;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.drawable.GradientDrawable;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;

import com.x.xiaoshuo.R;
import com.x.xiaoshuo.ui.dialog.AutoReadDialog;
import com.x.xiaoshuo.utils.ToastUtils;
import com.x.xiaoshuo.widget.readview.BookStatus;

import static android.animation.ValueAnimator.INFINITE;


public class AutoReadAim implements AimInterface {
    private Path mPath0;

    protected Bitmap mCurPageBitmap, mNextPageBitmap;
    protected Canvas mCurrentPageCanvas, mNextPageCanvas;

    GradientDrawable mBackShadowDrawableTB;

    ReadView readView;

    final int FASTEST_TIME = 6;
    final int FASTEST_LEVEL = 20;

    int duration = 6;

    int level = 20;

    ValueAnimator animator;

    AutoReadDialog autoReadDialog;

    boolean mPaused = false;

    boolean mStop = false;


    protected PointF mCurTouch = new PointF();

    public AutoReadAim(ReadView readView) {

        mCurTouch.x = 0.01f;
        mCurTouch.y = 0.01f;

        mPath0 = new Path();

        int[] mBackShadowColors = new int[]{0xaa666666, 0x666666};
        mBackShadowDrawableTB = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, mBackShadowColors);
        mBackShadowDrawableTB.setGradientType(GradientDrawable.LINEAR_GRADIENT);

        mCurPageBitmap = Bitmap.createBitmap(readView.mScreenWidth, readView.mScreenHeight, Bitmap.Config.RGB_565);
        mNextPageBitmap = Bitmap.createBitmap(readView.mScreenWidth, readView.mScreenHeight, Bitmap.Config.RGB_565);
        mCurrentPageCanvas = new Canvas(mCurPageBitmap);
        mNextPageCanvas = new Canvas(mNextPageBitmap);

        this.readView = readView;
    }

    @Override
    public void drawNextPageAreaAndShadow(Canvas canvas) {
        canvas.drawBitmap(mCurPageBitmap, 0, 0, null);
        mPath0.reset();
        canvas.save();
        mPath0.moveTo(0, 0);
        mPath0.lineTo(0, mCurTouch.y);
        mPath0.lineTo(readView.mScreenWidth, mCurTouch.y);
        mPath0.lineTo(readView.mScreenWidth, 0);
        mPath0.lineTo(0, 0);
        mPath0.close();
        canvas.clipPath(mPath0);
        canvas.drawBitmap(mNextPageBitmap, 0, 0, null);
        try {
            canvas.restore();
        } catch (Exception e) {

        }
        canvas.save();
        GradientDrawable shadow;
        shadow = mBackShadowDrawableTB;
        shadow.setBounds(0, (int) mCurTouch.y - 5, (int) (readView.mScreenWidth), (int) (mCurTouch.y + 5));
        shadow.draw(canvas);
        try {
            canvas.restore();
        } catch (Exception e) {

        }
    }

    @Override
    public void drawCurrentPageShadow(Canvas canvas) {

    }

    @Override
    public void drawCurrentBackArea(Canvas canvas) {

    }

    @Override
    public void drawCurrentPageArea(Canvas canvas) {

    }

    @Override
    public void calcPoints() {

    }

    @Override
    public void calcCornerXY(float x, float y) {

    }

    @Override
    public void startAnimation() {
        int duration = (int) ((((FASTEST_LEVEL - level) + 0.5f + FASTEST_TIME) * 1000) * (readView.mScreenHeight - mCurTouch.y) / readView.mScreenHeight);
        if (mCurTouch.y > 30) {
            animation(duration);
        } else {
            mCurrentPageCanvas.drawBitmap(readView.mCurPageBitmap, 0, 0, null);
            BookStatus status = readView.pagefactory.nextPage();
            if (status == BookStatus.NO_NEXT_PAGE) {
                ToastUtils.showSingleToast("没有下一页啦");
            } else if (status == BookStatus.LOAD_SUCCESS) {
                readView.pagefactory.onDraw(mNextPageCanvas);
                animation(duration);
            }
        }
    }

    private void animation(int duration) {
        mPaused = false;
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        if (mCurTouch.y > 30) {
            animator = ValueAnimator.ofFloat(mCurTouch.y, readView.mScreenHeight);
            animator.setInterpolator(new LinearInterpolator());
            animator.setRepeatCount(0);
            animator.setDuration(duration).start();
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    if (!mPaused) {
                        mCurTouch.x = 0.01f;
                        mCurTouch.y = 0.01f;
                        startAnimation();
                    }
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        } else {
            animator = ValueAnimator.ofFloat(0, readView.mScreenHeight);
            animator.setRepeatCount(INFINITE);
            animator.setInterpolator(new LinearInterpolator());
            animator.setDuration(duration).start();
            animator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                    if (!mPaused) {
                        readView.pagefactory.onDraw(mCurrentPageCanvas);
                        BookStatus status = readView.pagefactory.nextPage();
                        if (status == BookStatus.NO_NEXT_PAGE) {
                            ToastUtils.showSingleToast("没有下一页啦");
                            animation.cancel();
                        } else if (status == BookStatus.LOAD_SUCCESS) {
                            readView.pagefactory.onDraw(mNextPageCanvas);

                        }
                    }
                }
            });
        }

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float y = (float) animation.getAnimatedValue();
                mCurTouch.y = y;
                readView.postInvalidate();
            }
        });
    }

    @Override
    public void abortAnimation() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        mCurTouch.x = 0.01f;
        mCurTouch.y = 0.01f;
        readView.mTouch.x = 0.01f;
        readView.mTouch.y = 0.01f;
        mPaused = false;
        mStop = false;
    }


    public void pauseAnimation() {
        if (animator != null && animator.isRunning()) {
            mPaused = true;
            animator.cancel();
            if (autoReadDialog == null) {
                autoReadDialog = new AutoReadDialog(readView.getContext());
                autoReadDialog.setLevelVlue(level);
                autoReadDialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.plus) {
                            setLevel(level++);
                            autoReadDialog.setLevelVlue(level);

                        } else if (i == R.id.minor) {
                            setLevel(level--);
                            autoReadDialog.setLevelVlue(level);

                        } else if (i == R.id.cannel) {
                            mStop = true;
                            autoReadDialog.dismiss();
                            readView.abortAnimation();
                            Toast.makeText(readView.getContext(), "退出自动阅读", Toast.LENGTH_SHORT).show();

                        }
                    }
                });
                autoReadDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (!mStop) {
                            startAnimation();
                        }
                        mStop = false;
                    }
                });
            }
            autoReadDialog.show();
        }
    }

    public void setLevel(int level) {
        this.level = this.level > FASTEST_LEVEL ? FASTEST_LEVEL : this.level;
        this.level = this.level < 1 ? 1 : this.level;
    }

    @Override
    public void restoreAnimation() {

    }

    @Override
    public void setBitmaps(Bitmap mCurPageBitmap, Bitmap mNextPageBitmap) {

    }

    @Override
    public void setTheme(int theme) {

    }

    @Override
    public void computeScroll() {
    }

    @Override
    public void jumpToChapter(int chapter) {

    }

    @Override
    public void destory() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        if (mCurPageBitmap != null && !mCurPageBitmap.isRecycled()) {
            mCurPageBitmap.recycle();
        }

        if (mNextPageBitmap != null && !mNextPageBitmap.isRecycled()) {
            mNextPageBitmap.recycle();
        }
    }

    class AutoInterpolator implements Interpolator {

        @Override
        public float getInterpolation(float input) {
            return input;
        }
    }
}
